/**
 * 
 */

package com.shy.portal.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.shy.base.controller.AbsController;
import com.shy.base.vo.AppConstants;
import com.shy.portal.entity.Permission;
import com.shy.portal.entity.Role;
import com.shy.portal.entity.RolePermission;
import com.shy.portal.service.PermissionService;
import com.shy.portal.service.RolePermissionService;
import com.shy.portal.service.RoleService;
import com.shy.portal.vo.MenuPermissionVo;
import com.shy.portal.vo.PermissionVo;

/**
 * <p>
 * Title: RoleController
 * </p>
 * <p>
 * Description:角色信息管理控制器
 * </p>
 * <p>
 * Company:ipebg
 * </p>
 * 
 * @author H2013788
 */
@Controller
@RequestMapping("/role_permission")
public class RolePermissionController extends AbsController {

	/**
     * log
     */
	private Logger logger = LogManager.getLogger(this.getClass());
    
    /**
     * 角色service层
     */
    @Resource
    private RoleService roleService;
    
    /**
     * 权限service层
     */
    @Resource
    private PermissionService permissionService;
    
    /**
     * 角色权限service层
     */
    @Resource
    private RolePermissionService rolePermissionService;

    /**
     * 编辑角色权限，查询权限列表
     * @param roleId 角色ID
     * @param response 反饋
     * @author H2201965
     * @date 2018/2/6下午2:52:09
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/load_role_permission")
    public void editRolePermission(Integer roleId, HttpServletResponse response) {
        // 所有权限列表
        List<Permission> permissionList = permissionService.listByPager(null, null,
                getPageableByNoPage()).getObjs();
        //List<RolePermission> rolePermissionList = null;
        List<Permission> rolePermissionList = null;
        if (null != roleId) {
           /* Role role = roleService.getById(roleId);
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRole(role);
            // 当前角色具有的权限列表
            rolePermissionList = rolePermissionService.getByPager(rolePermission,
                    getPageableByNoPage()).getObjs();*/
            rolePermissionList = permissionService.getPermissionsByRoleId(roleId);
        }
        List<MenuPermissionVo> list = buildPermissionVoList(permissionList, rolePermissionList);
        Gson gson = new Gson();
        writeResponse(new StringBuffer(gsonDateTime.toJson(list)), response);
    }

    /**
     * 保存角色权限
     * @param permissionIds 权限ID
     * @param roleId 角色ID
     * @param response 反饋
     * @author H2201965
     * @date 2018/2/6下午2:52:30
     */
    @RequestMapping("/save_role_permission")
    public void saveRolePermission(Integer[] permissionIds, Integer roleId,
            HttpServletResponse response) {
        boolean result = false;
        if (null != permissionIds && permissionIds.length > 0) {
            List<RolePermission> list = new ArrayList<>();
            RolePermission rolePermission = null;
            Role role = new Role();
            role.setId(roleId);
            for (Integer permissionId : permissionIds) {
                rolePermission = new RolePermission();
                rolePermission.setRole(role);
                Permission permission = new Permission();
                permission.setId(permissionId);
                rolePermission.setPermission(permission);
                rolePermission.setCreateTime(new Date());
                rolePermission.setChecked(true);
                list.add(rolePermission);
            }
            try {
                result = rolePermissionService.batchSaveRolePermission(list, roleId);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(AppConstants.configMap.get(AppConstants.SAVE_ERROR) + e);
            }
        }
        if (result) {
            respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.SAVE_SUCCESS), response);
        } else {
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.SAVE_ERROR), response);
        }
    }

    /**
     * 输出权限列表,如果当前角色已具有，自动標示checked
     * 
     * @param permissionList 权限list
     * @param rolePermissionList 角色权限list
     * @return list
     * @author H2013788
     * @date 2017/11/15下午3:22:23
     */
    private List<MenuPermissionVo> buildPermissionVoList(List<Permission> permissionList,
            List<Permission> rolePermissionList) {
        List<MenuPermissionVo> listResult = new ArrayList<>();
        Map<String, List<PermissionVo>> map = new LinkedHashMap<String, List<PermissionVo>>();
        List<Integer> checkedPermissionIds = new ArrayList<>();
        if (null != rolePermissionList && !rolePermissionList.isEmpty()) {
            for (Permission permission : rolePermissionList) {
                checkedPermissionIds.add(permission.getId());
            }
        }
        for (Permission permission : permissionList) {
            PermissionVo permissionVo = new PermissionVo();
            permissionVo.setPermissionId(permission.getId());
            permissionVo.setPermissionName(permission.getPermissionName());
            permissionVo.setChecked(checkedPermissionIds.contains(permission.getId()));
            if (map.containsKey(permission.getMenu().getMenuName())) {
                List<PermissionVo> list = map.get(permission.getMenu().getMenuName());
                list.add(permissionVo);
                map.put(permission.getMenu().getMenuName(), list);
            } else {
                List<PermissionVo> list = new ArrayList<>();
                list.add(permissionVo);
                map.put(permission.getMenu().getMenuName(), list);
            }
        }

        Iterator<String> keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            List<PermissionVo> value = map.get(key);
            MenuPermissionVo mp = new MenuPermissionVo();
            mp.setMenuName(key);
            mp.setList(value);
            listResult.add(mp);
        }
        return listResult;
    }

}
